<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box">
            <div class="card">
                <div class="top_box">
                    <div class="split">基本信息</div>
                </div>
                <el-form
                    ref="ruleFormRef"
                    :model="formData"
                    label-width="80px"
                    :rules="rules"
                    style="width: 62%"
                    :disabled="pageType == 'look'">
                    <el-form-item label="产品名称" prop="product_name">
                        <el-input v-model="formData.product_name" placeholder="请输入产品名称" />
                    </el-form-item>
                    <el-form-item prop="product_no" label="产品编号">
                        <el-input
                            v-model="formData.product_no"
                            placeholder="请输入产品编号"
                            :disabled="pageType == 'edit'"
                            maxlength="25"
                            show-word-limit />
                    </el-form-item>
                    <el-form-item label="产品品类" prop="category_id">
                        <el-cascader
                            v-model="formData.category_id"
                            style="width: 100%"
                            :props="defaultProps"
                            :options="groupOptions"
                            placeholder="请输入产品品类" />
                    </el-form-item>
                    <el-form-item label="产品封面" prop="cover">
                        <div>
                            <el-upload
                                v-if="!formData.cover"
                                :on-change="(rawFile: any, key: string) => beforeAvatarUpload(rawFile, key, 2)"
                                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                                :show-file-list="false"
                                :auto-upload="false"
                                @click="getUploadKey(1)">
                                <div class="upload-box">
                                    <img src="@/assets/image/content/add-icon.png" alt="" style="margin-bottom: 12px" />
                                    <div>点击上传</div>
                                </div>
                            </el-upload>
                            <div v-else class="upload-file-box">
                                <el-image style="width: 100%; height: 100%" :src="formData.cover" fit="cover" />
                                <template v-if="pageType !== 'look'">
                                    <img
                                        class="del"
                                        src="@/assets/image/customer/close_icon.png"
                                        alt=""
                                        @click="delFile(1)" />
                                </template>
                            </div>
                            <div class="desc">
                                图片支持JPG、PNG、JPEG格式，大小2M以内，建议宽高比为1：1，尺寸200px*200px。
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="产品描述" prop="product_desc">
                        <div>
                            <div style="padding: 10px 0 0">
                                <el-input
                                    v-model="formData.product_desc"
                                    maxlength="500"
                                    show-word-limit
                                    :rows="4"
                                    type="textarea"
                                    placeholder="建议描述产品细节、购买须知等"
                                    class="content_input"
                                    style="width: 580px" />
                            </div>
                        </div>
                        <div></div>
                    </el-form-item>
                    <el-form-item label="产品详情图" label-width="90">
                        <div style="padding: 10px 0 0">
                            <div>
                                <el-upload
                                    v-if="!formData.images"
                                    :on-change="beforeAvatarUpload"
                                    accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                                    :show-file-list="false"
                                    :auto-upload="false"
                                    @click="getUploadKey(2)">
                                    <div class="upload-box" style="width: 300px; height: 160px">
                                        <img
                                            src="@/assets/image/content/add-icon.png"
                                            alt=""
                                            style="margin-bottom: 12px" />
                                        <div>点击上传</div>
                                    </div>
                                </el-upload>
                                <div v-else class="upload-file-box" style="width: 300px; height: 160px">
                                    <el-image style="width: 100%; height: 100%" :src="formData.images" fit="cover" />
                                    <template v-if="pageType !== 'look'">
                                        <img
                                            class="del"
                                            src="@/assets/image/customer/close_icon.png"
                                            alt=""
                                            @click="delFile(2)" />
                                    </template>
                                </div>
                                <div class="desc">图片支持JPG、PNG、JPEG格式，大小5M以内。</div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="上架状态">
                        <div>
                            <el-switch v-model="formData.state" class="ml-2" :active-value="2" :inactive-value="1" />
                        </div>
                    </el-form-item>
                    <div class="top_box">
                        <div class="split">规格参数</div>
                    </div>
                    <el-form-item label="规则参数" prop="spec_type">
                        <el-radio v-model="formData.spec_type" :label="1">统一规格</el-radio>
                        <el-radio v-model="formData.spec_type" :label="2">多规格</el-radio>
                    </el-form-item>
                    <blockquote v-if="formData.spec_type == 1">
                        <el-form-item label="售卖价格" prop="sale_price">
                            <el-input
                                v-model="formData.sale_price"
                                placeholder="请输入售卖价格"
                                class="splits"
                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')" /><span>元</span>
                        </el-form-item>
                        <el-form-item label="成本价格" prop="cost_price">
                            <el-input
                                v-model="formData.cost_price"
                                placeholder="请输入成本价格"
                                class="splits"
                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')" /><span>元</span>
                        </el-form-item>
                        <el-form-item label="总库存" prop="stock_qty">
                            <el-input
                                v-model="formData.stock_qty"
                                placeholder="请输入库存"
                                class="splits"
                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')" /><span>件</span>
                        </el-form-item>
                    </blockquote>
                    <!-- 多规格 -->
                    <blockquote v-else>
                        <el-form-item>
                            <div v-if="isShow" class="box">
                                <div
                                    v-for="(item, index) in tempData"
                                    :key="index"
                                    style="display: flex; margin-bottom: 16px">
                                    <div class="box_left">{{ `规格${index + 1}：` }}</div>
                                    <div class="box_right">
                                        <div class="specs_name">
                                            <el-input
                                                v-model="item.name"
                                                placeholder="请输入参数名称"
                                                maxlength="5"
                                                show-word-limit
                                                style="width: 240px" />
                                            <span class="del_icon" @click="onRemove(index)">
                                                <template v-if="pageType !== 'look'">
                                                    <el-icon><Delete /></el-icon>
                                                </template>
                                            </span>
                                        </div>
                                        <div>
                                            <el-input
                                                v-model="item.inputValue"
                                                placeholder="请输入自定义的值"
                                                maxlength="15"
                                                show-word-limit
                                                style="width: 380px; margin: 16px 0" />
                                            <!-- <div style="display: inline-block; margin-left: 8px" class="btn_item" @click="confirmAdd(index)">确认添加</div> -->
                                            <el-button
                                                style="display: inline-block; margin-left: 8px"
                                                @click="confirmAdd(index)"
                                                >确认添加</el-button
                                            >
                                        </div>
                                        <div class="specs_box">
                                            <div
                                                v-if="
                                                    formData.specificate[index] &&
                                                    formData.specificate[index].options.length !== 0
                                                ">
                                                <el-checkbox
                                                    v-for="option in formData.specificate[index].options"
                                                    :key="option.name"
                                                    v-model="option.active"
                                                    :label="option.name"
                                                    @change="checkboxHandler(option)" />
                                            </div>
                                            <span v-else>未添加自定义参数</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- <div class="btn_item" @click="addSpecs">添加规格</div> -->
                            <el-button @click="addSpecs">添加规格</el-button>
                            <el-form-item v-if="formData.specificate_list[0]?.options_vals">
                                <div class="specstop_box">
                                    <span>规格明细</span>
                                    <el-button type="primary" plain @click="batchPopupShow">批量设置</el-button>
                                </div>
                                <el-table
                                    :data="formData.specificate_list"
                                    stripe
                                    row-key="options_vals"
                                    style="width: 100%"
                                    :header-cell-style="{ background: '#F9F9F9', color: '#909399' }">
                                    <el-table-column prop="options_vals" label="规格信息" />
                                    <el-table-column prop="sale_price" label="售卖价格" align="left">
                                        <template #default="scope">
                                            <!-- {{ scope.row }} -->
                                            <el-input
                                                v-model="scope.row.sale_price"
                                                class="specs_frame"
                                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')" /><span
                                                >元</span
                                            >
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="cost_price" label="成本价格" align="left">
                                        <template #default="scope">
                                            <el-input
                                                v-model="scope.row.cost_price"
                                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')"
                                                class="specs_frame" /><span>元</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="stock_qty" label="总库存" align="left">
                                        <template #default="scope">
                                            <el-input
                                                v-model="scope.row.stock_qty"
                                                oninput="value=value.replace(/[^\d]/g,'').replace(/^0{1,}/g, '')"
                                                class="specs_frame" /><span>件</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>
                        </el-form-item>
                    </blockquote>
                </el-form>
            </div>
            <BatchPopup ref="BatchPopupRef" @updateData="updateData" />
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" :disabled="pageType == 'look'" @click="onSubmit">保存</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, watch } from 'vue';
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import { uploadFile2 } from '@/api/common';
import {
    productCreate,
    CatetList,
    productInfo,
    productEdit,
    getLastProductCate
} from '@/api/salesleads/productmanagement/product';
import BatchPopup from '../components/BatchPopup.vue';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref();
const BatchPopupRef = ref(null);
const isShow = ref(false);
let pageType = route.query.type;
const id = route.query.id;
let nowUploadKey: any = null;
const getUploadKey = (key: number) => {
    nowUploadKey = key;
};
const tempData = ref([]);
const formData = reactive({
    product_name: '', //产品名
    product_no: '', //产品编号
    category_id: [], //分类 all-全部
    cover: '', //产品封面图url
    product_desc: '', //产品描述
    images: '', //产品详情图
    state: 2, //上架状态 1-下架 2-上架
    spec_type: 1, //规格类型 1-无规格 2-多规格
    stock_qty: '', //总库存 spec_type=1必传
    cost_price: '', //成本价格 spec_type=1必传
    sale_price: '', //销售价格 spec_type=1必传
    specificate: [], //规格数据  spec_type=2必传
    specificate_list: [
        {
            options_vals: '', //规格信息 spec_type=2必传
            sale_price: 0, //售卖价格 spec_type=2必传
            cost_price: 0, //成本价格 spec_type=2必传
            stock_qty: 0 //总库存 spec_type=2必传
        }
    ] //规格明细数据 spec_type=2必传
});

// 交叉渲染
const whatever = (...arrs) => {
    return arrs.reduce((arr1, arr2) => arr1.flatMap(e => arr2.map(v => `${e}×${v}`)));
};

// 表格数据
const changeTable = () => {
    const arr = [];
    let temp = [];

    formData.specificate.forEach((v, i) => {
        temp = [];
        v.options.forEach((item, index) => {
            if (item.active) {
                temp.push(item.name);
            }
        });

        if (temp.length !== 0) {
            arr.push(temp);
        }
    });
    // 记录当前  加添的顺序和表格顺序不一致
    const origin_list = JSON.parse(JSON.stringify(formData.specificate_list));
    whatever(...arr).forEach((item, index) => {
        // red*l red*m blue*l blue*m 找到相同的属性值
        const current = origin_list.find(v => v.options_vals === item);
        // 找到了才赋值
        if (current) {
            formData.specificate_list[index] = { ...current, options_vals: item };
        } else {
            formData.specificate_list[index] = {
                options_vals: item, //规格信息 spec_type=2必传
                sale_price: 0, //售卖价格 spec_type=2必传
                cost_price: 0, //成本价格 spec_type=2必传
                stock_qty: 0 //总库存 spec_type=2必传
            };
        }
    });
};

// 添加规格
const addSpecs = () => {
    isShow.value = true;
    formData.specificate.push({
        inputValue: '',
        name: '',
        options: []
    });

    tempData.value.push({
        inputValue: '',
        name: '',
        options: []
    });
};
const resultData = ref();
// 确认添加规格
const confirmAdd = (index: number) => {
    const data: object = formData.specificate[index];
    const result = tempData.value[index];
    resultData.value = tempData.value[index];

    let flag = false;

    if (result.inputValue.trim().length === 0 || result.name.trim() === '') {
        flag = true;
        ElMessage.error('规格参数或自定义值不能为空');
    }

    if (!flag) {
        data.options.forEach((e, i) => {
            if (e.name == result.inputValue) {
                ElMessage.error(`参数名称为${e.name}的自定义值有重复！`);
                flag = true;
            }
        });
    }

    data.name = result.name;
    if (!flag) {
        data.options.push({ name: result.inputValue, active: true });
        result.inputValue = '';
    }
    changeTable();
};

// 删除
const onRemove = (index: number) => {
    tempData.value.splice(index, 1);
    formData.specificate.splice(index, 1);
    formData.specificate_list = [];
    changeTable();
};
// 多选
const checkboxHandler = option => {
    if (!option.active) {
        for (let i = 0; i < formData.specificate_list.length; i++) {
            const v = formData.specificate_list[i];
            if (v.options_vals.includes(option.name)) {
                formData.specificate_list.splice(i, 1);
                i--;
            }
        }
        changeTable();
    } else {
        changeTable();
    }
};

const rules = reactive({
    product_desc: [{ required: true, message: '请输入产品描述', trigger: 'blur' }],
    product_no: [{ required: true, message: '请输入产品编号', trigger: 'blur' }],
    product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
    spec_type: [{ required: true, trigger: 'change' }],
    sale_price: [{ required: true, message: '请输入销售价格', trigger: 'blur' }],
    cost_price: [{ required: true, message: '请输入成本价格', trigger: 'blur' }],
    stock_qty: [{ required: true, message: '请输入总库存', trigger: 'blur' }],
    category_id: [{ required: true, message: '请输入产品品类', trigger: 'change' }],
    cover: [{ required: true, message: '产品封面不能为空', trigger: 'change' }]
});
const groupOptions = ref([]);
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
const getCatetList = async (data: any) => {
    const res = await CatetList(data);
    groupOptions.value = res;
};
getCatetList();
// 上传图片的方法
const uploadFun = (file: any, fileName: string, key: string) => {
    uploadFile2({
        file,
        fileName
    }).then((r: any) => {
        if (nowUploadKey == 1) {
            formData.cover = r.url;
            return;
        }
        if (nowUploadKey == 2) {
            formData.images = r.url;
            return;
        }
    });
};
// 上传检验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any, key: string, size = 5) => {
    if (!rawFile) {
        return;
    }
    const types = ['.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'];
    if (!types.includes(rawFile.name.substring(rawFile.name.lastIndexOf('.')))) {
        ElMessage.error('图片格式不正确！');
        return false;
    }
    if (rawFile.size / 1024 / 1024 > size) {
        ElMessage.error(`上传图片大小不能超过${size}M`);
        return false;
    }
    uploadFun(rawFile.raw, rawFile.name, key);
};
const delFile = (val: number) => {
    if (val == 1) {
        formData.cover = '';
        return;
    }
    if (val == 2) {
        formData.images = '';
        return;
    }
};
// 保存
const onSubmit = () => {
    ruleFormRef.value.validate(async (valid, fileds) => {
        if (valid) {
            pageType == 'edit' ? await productEdit({ ...formData, product_id: id }) : await productCreate(formData);
            router.push('/salesleads/salesmanagement/productmanagement');
            ElMessage.success(pageType == 'edit' ? '编辑成功' : '新建成功');
        } else {
            ElMessage.error('请填完必填项');
        }
    });
};
// 批量设置
const batchPopupShow = () => {
    BatchPopupRef.value.drawer.show = true;
};
const updateData = (v: any) => {
    formData.specificate_list.forEach((item, i) => {
        item.sale_price = v.sale_price;
        item.cost_price = v.cost_price;
        item.stock_qty = v.stock_qty;
    });
};
// 查看
const getLook = async () => {
    const res = await productInfo({ product_id: id });
    if (res.spec_type == 2) {
        isShow.value = true;
    }
    formData.product_name = res.product_name;
    formData.product_no = res.product_no;
    formData.category_id = res.category_id;
    formData.cover = res.cover;
    formData.product_desc = res.product_desc;
    formData.images = res.images;
    formData.state = res.state;
    formData.spec_type = res.spec_type;
    formData.stock_qty = res.stock_qty;
    formData.cost_price = res.cost_price;
    formData.sale_price = res.sale_price;
    formData.specificate = res.specificate;
    tempData.value = JSON.parse(JSON.stringify(res.specificate));
    formData.specificate_list = res.specificate_list;
};
onMounted(() => {
    pageType = route.query.type;
    if (pageType) {
        getLook();
    } else {
        // 3303bug => 新增时，默认选择上次选中的品类
        getLastProductCate().then((res: any) => {
            formData.category_id = res.category_id;
        });
    }
});
defineExpose({
    formData
});
</script>

<style lang="scss" scoped>
.card {
    padding: 24px;
}

.top_box {
    margin-bottom: 24px;

    .split {
        font-size: 16px;
        color: #33302d;
        border-bottom: 1px solid #eaeaea;
        padding-bottom: 21px;
    }
}

.desc {
    font-size: 12px;
    font-family: STHeitiSC-Light, STHeitiSC;
    font-weight: 300;
    color: #969696;
    line-height: 1.4;
    margin-top: 10px;
}

.upload-box {
    width: 110px;
    height: 110px;
    text-align: center;
    border-radius: 4px;
    background: #f8f8f8;
    border: 1px solid #eaeaea;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    img {
        width: 20px;
        height: 20px;
    }

    div {
        width: 100%;
        line-height: 14px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #ff6b00;
    }
}

.upload-file-box {
    position: relative;
    width: 110px;
    height: 110px;
    border-radius: 4px;
    border: 1px solid #eaeaea;
    overflow: hidden;

    .del {
        position: absolute;
        width: 20px;
        height: 20px;
        top: 10px;
        right: 10px;
        cursor: pointer;
    }
}

.splits {
    width: 400px;
    margin-right: 10px;
}

.btn_box {
    position: absolute;
    background: #fff;
    bottom: 0;
    right: 15px;
    text-align: center;
    width: calc(100% - 32px);

    :deep(.el-card__body) {
        padding: 14px 20px;
    }
}

.btn_item {
    width: 60px;
    padding: 0 22px;
    margin: 0 8px 12px 0;
    text-align: center;
    background: #f9f9f9;
    border-radius: 2px;
    border: 1px solid #eaeaea;
    cursor: pointer;
    font-size: 14px;
    margin-top: 24px;
}

.box {
    // display: flex;
    .box_right {
        .specs_name {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .del_icon {
                cursor: pointer;
            }
        }

        .specs_box {
            background: rgb(248 248 248);
            border-radius: 4px;
            min-height: 46px;
            line-height: 46px;
            padding: 0 18px;
        }
    }
}

.specs_frame {
    width: 100px;
    margin-right: 8px;
}

.specstop_box {
    display: flex;
    justify-content: space-between;
    margin: 24px 0;
}
</style>
